package com.kummuna.ui;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.Facebook.DialogListener;
import com.kummuna.R;
import com.kummuna.R.layout;
import com.kummuna.R.menu;
import com.kummuna.config.MainConfiguration;
import com.kummuna.util.facebook.UserFunctions;
import com.kummuna.util.image.Utility;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.widget.ImageView;
import android.widget.TextView;

public class LoginFacebook extends Activity {
	
	private Facebook facebook;
	private AsyncFacebookRunner asynRunner;
	private Handler handler;
	private TextView text;
	private ImageView imgUserPic;
	public String App_id;
	public String fontpath;
	public Typeface tf;

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_facebook);
		
		 
		
		
		handler =new Handler();
		text=(TextView)findViewById(R.id.text);
	    imgUserPic=(ImageView)findViewById(R.id.user_pic);
	    
	    MainConfiguration app=new MainConfiguration();
	    App_id=app.facebookAppId;
	    fontpath=app.fontPath;
	 // Loading Font Face
        tf = Typeface.createFromAsset(getAssets(), fontpath);
 
      
		
		facebook=new Facebook(App_id);
		
		asynRunner =new AsyncFacebookRunner(facebook);
	
		facebook.authorize(this, new String[] {"publish_stream", "read_stream", "offline_access"},Facebook.FORCE_DIALOG_AUTH, new DialogListener(){
		//facebook.authorize(this, new DialogListener(){
	     @Override
	     public void onComplete(Bundle values){
	     
	   //  text.setText("กำลังดึงชื่อและภาพโปรไฟล์.....");
	     //set font
	     text.setTypeface(tf);
	     Bundle params=new Bundle();
	     params.putString("fields", "name, picture,id");
	     asynRunner.request("me", params,new UserRequestListener());
	   
	    
	     
	     }

		@Override
		public void onFacebookError(FacebookError e) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onError(DialogError e) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onCancel() {
			// TODO Auto-generated method stub
			 Intent LoginMain=new Intent(getApplicationContext(),MainActivity.class);
		     startActivity(LoginMain);
		}
	     
		});
	     
		}


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.login_facebook, menu);
		return true;
	}
	
	@Override
	public void onActivityResult(int requestCode,int resultCode,Intent data)
	{
		 super.onActivityResult(requestCode, resultCode, data);
		 facebook.authorizeCallback(requestCode, resultCode, data);
	}
	
	
	public  class UserRequestListener implements RequestListener{

		@Override
		public void onComplete(final String response,final Object state) {
			// TODO Auto-generated method stub
			 JSONObject jsonObject;
			
		
			try{
				jsonObject=new JSONObject(response);
				Log.d("response write ", "text = "+response);
				final String name=jsonObject.getString("name");
				final String id=jsonObject.getString("id");
				JSONObject obj = jsonObject.getJSONObject("picture").getJSONObject("data");
	            final String picURL = obj.getString("url");
				
	          //insert Data
                UserFunctions func=new UserFunctions();
                JSONObject getUserjson=func.loginUser(name, id, picURL);
	            final String uid=getUserjson.getJSONObject("Data").getString("Id");
	            final String uname=getUserjson.getJSONObject("Data").getString("Name");
	            final String img=getUserjson.getJSONObject("Data").getString("Image");
				
				new Thread(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub					
						final Bitmap bitmap=Utility.getBitmap(img);
						handler.post(new Runnable() {
							public void run() {	
									//text.setText(uid+" "+uname);
									//text.setTypeface(tf);
									//imgUserPic.setImageBitmap(bitmap);	
									 Intent Gmap=new Intent(getApplicationContext(),Detectivemap.class);
								     Gmap.putExtra("uid",uid);
								     Gmap.putExtra("uname",uname);
								     Gmap.putExtra("img",img);
								     Gmap.putExtra("flag", "1");
									 startActivity(Gmap);
							}
						});
					}
				}).start();
		
				
			}
			catch(JSONException ex)
			{
				ex.printStackTrace();
			}
			
		}

		@Override
		public void onIOException(IOException e, Object state) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onFileNotFoundException(FileNotFoundException e, Object state) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onMalformedURLException(MalformedURLException e, Object state) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onFacebookError(FacebookError e, Object state) {
			// TODO Auto-generated method stub
			
		}
		
		

	}

}
